<template>
  <section class="coupon-list">
    <section class="header">
      <a-page-header title="优惠券管理" />
    </section>
    <section class="content">
      <!-- 筛选栏 -->
      <section class="staticis">
        <a-form layout="vertical">
          <a-row :gutter="[32, 32]" :wrap="true" align="bottom">
            <a-col :span="$store.getters.isMobile ? 12 : 4">
              <a-form-item label="优惠券名称">
                <a-input
                  v-model:value="searchParams.name"
                  placeholder="请输入优惠券名称"
                  class="w-100p"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : 4">
              <a-form-item label="费用类型">
                <a-cascader
                  v-model:value="searchParams.cost_type"
                  :options="costTypeOption"
                  :load-data="getCostTypeSub"
                  placeholder="请选择绑定的费用类型"
                  dropdownClassName="fee-type-cascader-custom"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : 4">
              <a-form-item label="优惠券状态">
                <a-select
                  v-model:value="searchParams.status"
                  placeholder="请选择优惠券状态"
                  :options="couponStatus"
                  allowClear
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col>
              <a-space>
                <a-button type="primary" @click="searchClick">查询</a-button>
                <a-button @click="resetClick">重置</a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </section>

      <!-- 表格 -->
      <a-table
        sticky
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        class="mt-10"
      >
        <template #title>
          <a-row
            type="flex"
            justify="space-between"
            align="middle"
            class="table-header"
          >
            <a-col> 优惠券列表 </a-col>
            <a-col>
              <a-space>
                <a-button type="primary" @click="addCoupon">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  添加优惠券
                </a-button>

                <a-button
                  class="primary-yellow-btn"
                  type="primary"
                  @click="issueCoupon"
                >
                  <template #icon>
                    <MoneyCollectOutlined />
                  </template>
                  发放优惠券
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </template>

        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="viewRecord(record.id)"
              >领取记录</a-button
            >
            <a-button type="link" danger @click="delCoupon(record.id)">
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </section>
  </section>

  <!-- 添加优惠券 -->
  <AddCoupon
    :visible="addVisible"
    @closeModal="addVisible = false"
    @addSuccess="addSuccess"
  />

  <!-- 发放优惠券 -->
  <IssueCoupon
    :visible="issueVisible"
    @closeModal="issueVisible = false"
    @successGrant="issueVisible = false"
  />

  <!-- 领取记录 -->
  <RecordList
    :visible="recordVisible"
    :id="recordId"
    @closeModal="recordVisible = false"
  />
</template>

<script>
import { defineComponent, ref, computed, reactive, toRefs } from "vue";
import request from "@/common/utils/request";
import { useRouter } from "vue-router";
import { Form, message } from "ant-design-vue";
import store from "@/store";
const useForm = Form.useForm;
import { PlusOutlined, MoneyCollectOutlined } from "@ant-design/icons-vue";
import AddCoupon from "@/views/bill/CouponManagement/modules/AddCoupon.vue";
import IssueCoupon from "@/views/bill/CouponManagement/modules/IssueCoupon.vue";
import utils from "@/common/utils/utils";
import RecordList from "@/views/bill/CouponManagement/modules/RecordList.vue";

export default defineComponent({
  name: "couponManagement",
  components: {
    AddCoupon,
    IssueCoupon,
    PlusOutlined,
    MoneyCollectOutlined,
    RecordList,
  },
  props: {},
  setup(props) {
    const $router = useRouter();
    // 筛选
    const searchParams = reactive({
      name: "",
      cost_type: undefined, // 费用类型
      status: 3,
    });
    const { resetFields } = useForm(searchParams, {});

    const state = reactive({
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      dataList: [],
      costTypeOption: [],
      addVisible: false,
      issueVisible: false,
      recordId: 0,
      recordVisible: false,
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getTableData();
    };

    const getTableData = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
      }
      let params = {
        page: state.page,
        limit: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          if (!(key === "status" && searchParams[key] === 3)) {
            params[key] = searchParams[key];
          }
        }
      }
      if (params.cost_type && params.cost_type.length == 2) {
        params.cost_type = params.cost_type[1];
      }
      request
        .post("/org", "/coupon/list", { ...params })
        .then((res) => {
          state.dataList = res?.list || [];
          state.total = res?.total || 0;
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const addSuccess = () => {
      state.addVisible = false;
      getTableData();
    };

    // 搜索
    const searchClick = () => {
      getTableData(true);
    };
    const resetClick = () => {
      resetFields();
      getTableData(true);
    };

    // 添加优惠券
    const addCoupon = () => {
      state.addVisible = true;
    };

    // 发放优惠券
    const issueCoupon = () => {
      state.issueVisible = true;
    };

    // 删除
    const delCoupon = (id) => {
      utils.modalConfirm({
        content: "确认删除该优惠券吗？",
        centered: true,
        okType: "danger",
        onOk: () => {
          request
            .del("/org", "/coupon/del", {
              id: id,
            })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getTableData();
            });
        },
      });
    };

    // 查看领取记录
    const viewRecord = (id) => {
      if (id) {
        state.recordId = id;
        state.recordVisible = true;
      }
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
        .get("/org", "/bill/costList", {
          page: 1,
          limit: 9999,
          category_id: targetOption.value,
          status: 1,
        })
        .then((res) => {
          if (res.list) {
            targetOption.loading = false;
            targetOption.children = res.list.map((item) => ({
              label: item.name,
              value: item.cost_type,
              isLeaf: true,
            }));
            state.costTypeOption = [...state.costTypeOption];
          }
        });
    };

    const init = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          state.costTypeOption = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
        getTableData(true);
      });
    };

    init();

    return {
      columns,
      pagination,
      searchParams,
      couponStatus,
      ...toRefs(state),
      handleTableChange,
      searchClick,
      resetClick,
      addCoupon,
      getCostTypeSub,
      issueCoupon,
      delCoupon,
      viewRecord,
      addSuccess,
    };
  },
});

const LIFE_SPAN_OPTIONS = [
  {
    value: "date_1",
    label: "领取后当天有效",
  },
  {
    value: "date_2",
    label: "同活动结束时间",
  },
  {
    value: "date_3",
    label: "自定义有效天数",
  },
];

const columns = [
  {
    title: "优惠券名称",
    key: "name",
    dataIndex: "name",
    width: 200,
    fixed: "left",
    align: "center",
  },
  {
    title: "所属项目",
    dataIndex: "village_name",
    key: "village_name",
    width: 240,
    align: "center",
  },
  {
    title: "优惠券金额",
    dataIndex: "amount",
    key: "amount",
    width: 150,
    customRender: ({ text, record, index }) => {
      return record.attribute == 1
        ? `￥${record.amount}`
        : record.attribute == 2
        ? `${record.amount}折`
        : "--";
    },
    align: "center",
  },
  {
    title: "优惠条件",
    dataIndex: "condition",
    key: "condition",
    width: 200,
    customRender: ({ text, record, index }) => {
      return record?.use_premise?.condition === "billPrice"
        ? `满￥${record?.use_premise?.num || 0}可用`
        : record?.use_premise?.condition === "billMonth"
        ? `缴纳账单满足${record?.use_premise?.num || 0}个月可用`
        : record?.use_premise?.condition === "billCount"
        ? `满${record?.use_premise?.num || 0}个账单可用`
        : "--";
    },
    align: "center",
  },
  {
    title: "可用的费用类型",
    dataIndex: "cost_names",
    key: "cost_names",
    width: 240,
    align: "center",
    customRender: ({ text, record, index }) => {
      return text?.length ? text.join("、") : "";
    },
  },
  {
    title: "优惠券数量",
    dataIndex: "num",
    key: "num",
    width: 150,
    customRender: ({ text, record, index }) => {
      return text || "无限制";
    },
    align: "center",
  },
  {
    title: "券有效期",
    dataIndex: "effective_date",
    key: "effective_date",
    width: 150,
    customRender: ({ text, record, index }) => {
      return record?.effective_date?.valide_date === "date_3"
        ? `领取后${record?.effective_date?.day || 0}天内有效`
        : LIFE_SPAN_OPTIONS.find(
            (v) => v.value === record?.effective_date?.valide_date
          )?.label || "--";
    },
    align: "center",
  },
  {
    title: "每用户领取上限",
    dataIndex: "got_num",
    key: "got_num",
    width: 150,
    customRender: ({ text, record, index }) => {
      return text || "无限制";
    },
    align: "center",
  },
  {
    title: "活动有效期",
    dataIndex: "start_time",
    key: "start_time",
    width: 240,
    customRender: ({ text, record, index }) => {
      return record?.start_time + "~" + record?.end_time;
    },
    align: "center",
  },
  {
    dataIndex: "id",
    key: "action",
    title: "操作",
    width: 200,
    fixed: "right",
    align: "center",
  },
];

const couponStatus = [
  {
    value: 3,
    label: "全部",
  },
  {
    value: 0,
    label: "未生效",
  },
  {
    value: 1,
    label: "生效中",
  },
  {
    value: 2,
    label: "已到期",
  },
];
</script>

<style lang="less" scoped>
.coupon-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    height: 50px;
    background: #fff;
    &:deep(.ant-page-header) {
      padding: 10px 20px;
    }
  }
  .table-header {
    margin: 0 20px;
    color: rgba(0, 0, 0, 0.8);
  }
  .content {
    margin-top: 10px;
    padding: 10px;
  }
  .staticis {
    background: #fff;
    width: 100%;
    padding: 15px;
    margin-bottom: 10px;
  }
  .form-width {
    width: 100%;
  }
}
.border {
  border: 1px solid #f0f0f0;
}
:deep(.ant-form-item) {
  margin-bottom: 0;
}
.primary-yellow-btn {
  background-color: #f59a23;
  border-color: #f59a23;
  &:hover {
    background-color: #f7ad4d;
    border-color: #f7ad4d;
  }
  &:active {
    background-color: #f59a23;
    border-color: #f59a23;
  }
  &:focus {
    background-color: #f7ad4d;
    border-color: #f7ad4d;
  }
}
</style>
